<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车辆类型" prop="type" label-width="100px">
        <el-select v-model="queryParams.type" placeholder="请选择车辆类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="车牌号" prop="licensePlate">-->
<!--        <el-input-->
<!--          v-model="queryParams.licensePlate"-->
<!--          placeholder="请输入车牌号"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['report:car:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['report:car:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['report:car:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['report:car:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="licensePlate"  />
      <el-table-column label="车辆类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="容量(升)" align="center" prop="capacity"  />
      <el-table-column label="长度(米)" align="center" prop="length"  />
      <el-table-column label="宽度(米)" align="center" prop="remark"  />
      <el-table-column label="高度(米)" align="center" prop="height"  />
      <el-table-column label="部门" align="center" prop="deptId" :formatter="deptIdFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['report:car:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['report:car:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </el-col>
    </el-row>
    <!-- 添加或修改加油车信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="车牌号" prop="licensePlate" >
          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" style="width: 200px" />
<!--          <LicensePlate v-model="form.licensePlate" @change="change"></LicensePlate>-->
        </el-form-item>

        <el-form-item label="车辆类型" prop="type" >
          <el-select v-model="form.type" placeholder="请选择加油车类型" style="width: 200px">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>-->




        <el-form-item label="长度(米)" prop="length">
          <el-input-number v-model="form.length" placeholder="请输入长度"  :precision='4' style="width: 200px">
          </el-input-number>
          </el-form-item>
          <el-form-item label="宽度(米)" prop="remark">
            <el-input-number v-model="form.remark" placeholder="请输入宽度"  :precision='4' style="width: 200px">
            </el-input-number>
             </el-form-item>

        <el-form-item label="高度(米)" prop="height">
          <el-input-number v-model="form.height" placeholder="请输入高度"  :precision='4' style="width: 200px">
          </el-input-number>
          </el-form-item>


        <el-form-item label="容量(升)" prop="capacity" v-if="form.type!=1">
          <el-input-number v-model="form.capacity" placeholder="请输入容量"  :precision='4' style="width: 200px">
          </el-input-number>
          </el-form-item>

        <el-form-item label="归属部门" prop="deptId" v-if="checkRole(['admin'])">
          <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="width: 200px"/>
        </el-form-item>

<!--        <el-form-item label="车牌号" prop="licensePlate">-->
<!--          <el-input v-model="form.licensePlate" placeholder="请输入车牌号" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="车牌号" prop="licensePlate" >-->
<!--        <LicensePlate v-model="form.licensePlate" @change="change"></LicensePlate>-->
<!--        </el-form-item>-->



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, getCar, delCar, addCar, updateCar, exportCar } from "@/api/report/car";
import { checkRole } from '@/utils/permission'
import Treeselect from '@riophae/vue-treeselect'
import { treeselect } from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: "Car",
  components: { Treeselect },
  data() {
    return {
      deptOptions:[],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加油车信息表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // id字典
      idOptions: [],
      // 名称字典
      nameOptions: [],
      // 备注字典
      remarkOptions: [],
      // 长度字典
      lengthOptions: [],
      // 高度字典
      heightOptions: [],
      // 容量字典
      capacityOptions: [],
      // 加油车类型字典
      typeOptions: [],
      // 预留字段字典
      extraOptions: [],
      // 车牌号字典
      licensePlateOptions: [],
      // 部门名称
      deptName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      tempDeptId:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        licensePlate: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // name: [
        //   { required: true, message: "名称不能为空", trigger: "blur" }
        // ],
        length: [
          { required: true, message: "长度不能为空", trigger: "blur" }
        ],
        height: [
          { required: true, message: "高度不能为空", trigger: "blur" }
        ],
        // capacity:[
        //   { required: true, message: "容量不能为空", trigger: "blur" }
        // ],
        remark: [
          { required: true, message: "宽度不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "车辆类型不能为空", trigger: "change" }
        ],
        licensePlate: [
          { required: true, message: "车牌号不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect()
    this.getDicts("${column.dictType}").then(response => {
      this.idOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.nameOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.remarkOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.lengthOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.heightOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.capacityOptions = response.data;
    });
    this.getDicts("car_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.extraOptions = response.data;
    });
    this.getDicts("${column.dictType}").then(response => {
      this.licensePlateOptions = response.data;
    });
  },
  watch: {
    'form.type'(newType, oldType) {
   if (newType==1){
     this.form.capacity=null
   }
    }
  },
  methods: {
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
        // console.log('this.deptOptions:' + JSON.stringify(this.deptOptions))
      })
    },
    checkRole,
    change(val){
      console.log(val.array)  //数组形式
      console.log(val.value)  //字符串形式
      console.log(val.pass)     //是否验证通过
    },
    /** 查询加油车信息列表 */
    getList() {
      this.loading = true;
      listCar(this.queryParams).then(response => {
        this.carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // id字典翻译
    idFormat(row, column) {
      return this.selectDictLabel(this.idOptions, row.id);
    },
    // 名称字典翻译
    nameFormat(row, column) {
      return this.selectDictLabel(this.nameOptions, row.name);
    },
    // 备注字典翻译
    remarkFormat(row, column) {
      return this.selectDictLabel(this.remarkOptions, row.remark);
    },
    // 长度字典翻译
    lengthFormat(row, column) {
      return this.selectDictLabel(this.lengthOptions, row.length);
    },
    // 高度字典翻译
    heightFormat(row, column) {
      return this.selectDictLabel(this.heightOptions, row.height);
    },
    // 容量字典翻译
    capacityFormat(row, column) {
      return this.selectDictLabel(this.capacityOptions, row.capacity);
    },
    // 加油车类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 预留字段字典翻译
    extraFormat(row, column) {
      return this.selectDictLabel(this.extraOptions, row.extra);
    },
    // 车牌号字典翻译
    licensePlateFormat(row, column) {
      return this.selectDictLabel(this.licensePlateOptions, row.licensePlate);
    },
    deptIdFormat(row, column) {
      const dept = this.findDeptById(this.deptOptions, row.deptId);
      if (dept) {
        return dept.label; // or any other property of `dept` that you want to display
      }
      return 'Department Not Found'; // Default value if the department is not found
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        remark: null,
        length: null,
        height: null,
        capacity: null,
        type: null,
        extra: null,
        licensePlate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.deptId =  this.tempDeptId;
      this.title = "添加加油车信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCar(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改加油车信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCar(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCar(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除加油车信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCar(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {

      this.download('report/car/export', {
        ...this.queryParams
      }, `car_${new Date().getTime()}.xlsx`)

      // const queryParams = this.queryParams;
      // this.$confirm('是否确认导出所有加油车信息数据项?', "警告", {
      //     confirmButtonText: "确定",
      //     cancelButtonText: "取消",
      //     type: "warning"
      //   }).then(() => {
      //     this.exportLoading = true;
      //     return exportCar(queryParams);
      //   }).then(response => {
      //     this.download(response.msg);
      //     this.exportLoading = false;
      //   }).catch(() => {});
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.tempDeptId=data.id
      this.getList();
    },
    findDeptById(deptOptions, deptId) {

      for (let dept of deptOptions) {
        console.log(dept.id)
        console.log(deptId)
        if ((dept.id + "") === deptId+"") {
          return dept;
        }
        if (dept.children && dept.children.length > 0) {
          const foundDept = this.findDeptById(dept.children, deptId);
          if (foundDept) {
            return foundDept;
          }
        }
      }
      return null; // If no matching department is found
    },
  }
};
</script>
